<template>
  <div v-if="visible" class="modal-overlay">
    <ListTitle :list-title="`申请单`" />

    <div class="dialog_main">
      <!-- 下方占据剩余空间的部分，也有背景图片 -->
      <div class="body-section">
        <!-- subbody-2 下方部分，内容展示 -->
        <div class="subbody-2">
          <div class="subbody-3">
            <!-- 空域使用需求 -->
            <!-- <div class="airspace-demand-content" :style="{ height: '90%' }"> -->
            <div class="airspace-demand-content">
              <!-- 表单部分 -->
              <div class="custom-form-content">
                <!-- 第一行 -->
                <div class="custom-form-row">
                  <div class="custom-form-item">
                    <label for="taskStartTime">申请单位</label>
                    <input id="taskStartTime" v-model="form.applicant" type="text" readonly />
                  </div>
                  <div class="custom-form-item">
                    <label for="flightFrequency">航空器型号</label>
                    <input id="flightFrequency" v-model="form.aircraftModel" type="text" readonly />
                  </div>
                </div>
                <!-- 第二行 -->
                <div class="custom-form-row">
                  <div class="custom-form-item">
                    <label for="taskStartTime">申请ID</label>
                    <input id="taskStartTime" v-model="stringTitle" type="text" readonly />
                  </div>
                  <div class="custom-form-item">
                    <label for="flightFrequency">申请时间</label>
                    <input id="flightFrequency" v-model="form.applicationTime" type="text" readonly />
                  </div>
                </div>
                <!-- 第三行 -->
                <div class="custom-form-row">
                  <div class="custom-form-item">
                    <label for="isReturn">是否往返</label>
                    <input id="isReturn" type="text" readonly :value="form.isRoundTrip === 1 ? '是' : '否'" />
                  </div>
                  <div class="custom-form-item">
                    <label for="taskType">任务类型</label>
                    <input id="taskType" v-model="form.taskType" type="text" readonly />
                  </div>
                </div>
                <!-- 第四行 -->
                <div class="custom-form-row">
                  <div class="custom-form-item">
                    <label for="taskStartTime">任务开始时间</label>
                    <input id="taskStartTime" v-model="form.taskStartTime" type="text" readonly />
                  </div>
                  <div class="custom-form-item">
                    <label for="taskEndTime">任务结束时间</label>
                    <input id="taskEndTime" v-model="form.taskEndTime" type="text" readonly />
                  </div>
                </div>
                <!-- 第五行 -->
                <div class="custom-form-row">
                  <div class="custom-form-item">
                    <label for="flightFrequency">飞行频次</label>
                    <input id="flightFrequency" v-model="form.flightFrequency" type="text" readonly />
                    <span class="custom-unit">{{ frequencyUnit }}</span> <!-- 显示单位 -->
                  </div>
                </div>

                <!-- 表格展示 -->
                <div class="regional_table table">
                  <!-- 判断多边形轨迹是否存在 -->
                  <!-- <template v-if="form.polygonalAirspace === 1"> -->
                  <template v-if="tableData.polygonal && tableData.polygonal.length > 0">
                    <div class="logo-text-container flex-row justify-between">
                      <img referrerpolicy="no-referrer" src="../assets/img/module1/logoleft.png" alt="Logo" />
                      <span class="logo-text">多边体形区域</span>
                    </div>
                    <el-table :data="tableData.polygonal" style="width: 100%" max-height="450">
                      <el-table-column label="#" width="50" align="right">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('polygonal', scope.row)">
                            {{ scope.row.wayId }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="多边形顶点集合" autowidth align="center">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('polygonal', scope.row)">
                            {{ scope.row.pointNames.join(', ') }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="飞行上限（m）" width="170" align="center">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('polygonal', scope.row)">
                            {{ scope.row.maxAltitude }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="飞行下限（m）" width="170" align="center">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('polygonal', scope.row)">
                            {{ scope.row.minAltitude }}
                          </span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>


                  <!-- 判断圆形轨迹是否存在 -->
                  <!-- <template v-if="form.circularAirspace === 1"> -->
                  <template v-if="tableData.circular && tableData.circular.length > 0">
                    <div class="logo-text-container flex-row justify-between">
                      <img referrerpolicy="no-referrer" src="../assets/img/module1/logoleft.png" alt="Logo" />
                      <span class="logo-text">圆柱形区域</span>
                    </div>
                    <el-table :data="tableData.circular" style="width: 100%" max-height="450">
                      <el-table-column label="#" width="50" align="right">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('polygonal', scope.row)">
                            {{ scope.row.wayId }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="经度" width="140" align="center">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('circular', scope.row)">
                            {{ formatCoordinate(scope.row.longitude) }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="纬度" width="140" align="center">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('circular', scope.row)">
                            {{ formatCoordinate(scope.row.latitude) }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="飞行上限（m）" width="140" align="center">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('circular', scope.row)">
                            {{ scope.row.maxAltitude }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="飞行下限（m）" width="140" align="center">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('circular', scope.row)">
                            {{ scope.row.minAltitude }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="半径（m）" autowidth align="center">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('circular', scope.row)">
                            {{ scope.row.radius }}
                          </span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>

                  <!-- 判断线形轨迹是否存在 -->
                  <!-- <template v-if="form.straightAirspace === 1"> -->
                  <template v-if="tableData.straight && tableData.straight.length > 0">
                    <div class="logo-text-container flex-row justify-between">
                      <img referrerpolicy="no-referrer" src="../assets/img/module1/logoleft.png" alt="Logo" />
                      <span class="logo-text">点线形区域</span>
                    </div>
                    <el-table :data="tableData.straight" style="width: 100%" max-height="450">
                      <el-table-column label="#" width="50" align="right">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('straight', scope.row)">
                            {{ scope.row.wayId }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="航迹点坐标" autowidth align="center">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('straight', scope.row)">
                            {{ scope.row.urlStrings.join(', ') }}
                          </span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>

                  <!-- 没有数据的情况 -->
                  <!-- <template v-if="form.circularAirspace !== 1 && form.polygonalAirspace !== 1 && form.straightAirspace !== 1"> -->
                  <template v-if="(!tableData.polygonal || tableData.polygonal.length === 0) &&
                    (!tableData.circular || tableData.circular.length === 0) &&
                    (!tableData.straight || tableData.straight.length === 0)">
                    <p style="color: white; font-weight: bold; text-align: center;">没有空域轨迹数据</p>
                  </template>
                </div>
              </div>
            </div>

            <!-- 添加分析结果显示区域 -->
            <!-- <div v-if="showAnalysisResults" class="analysis-results">
              <img src="@/assets/img/nav/关闭.png" alt="关闭" class="close-btn" @click="showAnalysisResults = false" />

              <div class="analysis-grid">
                <div class="analysis-item" v-for="(status, label) in analysisLabels" :key="label">
                  <span class="analysis-label">{{ label }}</span>
                  <span class="analysis-tag" :class="status">
                    {{
                      status === 'success'
                        ? '成功'
                        : status === 'failed'
                          ? '失败'
                          : status === 'analyzing'
                            ? '分析中'
                            : '待分析'
                    }}
                  </span>
                </div>
              </div>
            </div> -->
            <!-- 🔥 核心：点击分析后才动态展示的结果区域 -->
            <div v-if="showAnalysisResults" class="analysis-results">
              <!-- 右上角的关闭按钮 -->
              <img src="@/assets/img/nav/关闭.png" alt="关闭" class="close-btn" @click="showAnalysisResults = false" />

              <!-- 分析结果文本框（支持HTML渲染，实现分段和颜色） -->
              <div class="analysis-text-box">
                <!-- 分析中/分析完成/分析失败 状态切换 -->
                <div v-if="analyzing" class="analyzing-tip">
                  <span class="loading-icon">●</span> 正在进行空域分析，请稍候...
                </div>
                <div v-else-if="analysisError" class="error-tip">
                  <span class="error-icon">!</span> 分析请求失败，请重试
                </div>
                <div v-else v-html="analysisText"></div>
              </div>
            </div>

            <div class="module1-yhr-button-container">
              <button class="module1-yhr-custom-btn" @click="handleAnalyze" :loading="analyzing">分析</button>
              <button class="module1-yhr-custom-btn" @click="prepareReject">驳回</button>
              <button class="module1-yhr-custom-btn" @click="submitForm(1)">接收</button>
              <button class="module1-yhr-custom-btn" @click="closeDialog">关闭</button>
              <!-- <button class="module1-yhr-custom-btn" @click="openAnalyzeDialog">分析</button> -->
            </div>

            <CustomDialogReject v-if="rejectDialogVisible" :visible.sync="rejectDialogVisible"
              :applicationId="String(form.id)" @confirm-reject="handleFinalReject" @accept="handleAccept"
              :weatherStatus="weatherStatus" :airspaceStatus="airspaceStatus" />

          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import axios from 'axios';
import ListTitle from "../components/ListTitle";
import CustomDialogReject from "../components/CustomDialogReject.vue";
import { drawCylinderAreaM1, draw3DRectangularPipelineTrackM1, draw3DPolygonalPrismM1, drawSectorCylinder } from '@/utils/draw3D-module1.js';
import { draw3DRectangularPipelineTrackM1_2 } from '@/utils/draw3D-module6.js';

const baseApi = process.env.NODE_ENV === 'production'
  //? process.env.VUE_APP_REMOTE_API
  ? '/api'  // 使用代理路径
  : process.env.VUE_APP_REMOTE_API_MODULE1;

export default {
  components: {
    ListTitle,
    CustomDialogReject
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: "默认标题"
    },
    dialogData: {
      type: Object,
      required: true
    },
    viewer: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      currentView: 'userInfo', // 默认显示用户基本信息
      form: {
        // 用户信息
        applicationTime: '',
        applicant: '', // 申请单位
        contacts: '',  // 联系人
        telephone: '', // 联系电话
        aircraftManufacturer: '', // 航空器厂商
        aircraftModel: '', // 航空器型号
        aircraftType: '', // 航空器类型
        aircraftControlType: '', // 航空器管制类型
        maximumTakeoffWeight: '', // 最大起飞重量
        dimensionsOfAircraftInDeployedState: '', // 航空器尺寸（展开）
        // 空域使用需求
        airspaceUsageType: '',          // 空域使用类型
        maximumFlightAltitude: '',      // 飞行项高
        taskType: '',                   // 任务类型
        minimumFlightAltitude: '',      // 飞行底高
        taskStartTime: '',              // 任务开始时间
        isRoundTrip: '',                // 是否往返
        taskEndTime: '',                // 任务结束时间
        flightFrequency: '',            // 飞行频次
        takeoffLocationName: '',        // 起降机场（起飞）的名称
        takeoffLocationCode: '',        // 起飞机场编号
        takeoffLocationType: '',        // 起飞机场类型
        takeoffLocationCoordinates: '', // 起飞机场坐标
        landingLocationName: '',        // 起降机场（降落）的名称
        landingLocationCode: '',        // 降落机场编号
        landingLocationType: '',        // 降落机场类型
        landingLocationCoordinates: ''  // 降落机场坐标
      },
      frequencyUnit: '次/天',  // 默认单位
      tableData: [],
      isUserInfoSelected: true,
      isAirspaceDemandSelected: false,
      currentDrawEntities: [], //当前组件绘制的GIS数据
      stringTitle: null,
      analyzing: false, // 添加分析中状态
      showAnalysisResults: false,

      selectedRejectStatus: 2, // 标记是驳回状态
      rejectDialogVisible: false,
      rejectReasons: [], // 多选的原因
      adjustTimeRange: [], // 时间区间数组 [start, end]
      adjustUsingAirspace: '', // 空域建议
      weatherStatus: '',
      airspaceStatus: '',

      // 以下是优化新增缓存字段
      cachedRejectReasons: [],
      cachedTimeRange: [],
      cachedAirspaceAdvice: '',

      // 用于传给弹窗的 props
      rejectInitReasons: [],
      rejectInitTimeRange: [],
      rejectInitAirspaceAdvice: '',

      taskMatchStatus: 'pending',
      collisionRiskStatus: 'pending',
      airspaceGapStatus: 'pending',
      timeConflictStatus: 'pending',
      temporaryResponse: null,
      analysisError: false,
    };
  },
  computed: {
    // analysisLabels() {
    //   return {
    //     '任务类型匹配': this.taskMatchStatus,
    //     '碰撞风险评估': this.collisionRiskStatus,
    //     '空域间距评估': this.airspaceGapStatus,
    //     '时间冲突评估': this.timeConflictStatus
    //   };
    // },
    // 🔥 核心：生成带分段、颜色标签的HTML文本
    analysisText() {
      if (!this.temporaryResponse || !this.temporaryResponse.data?.data) return '';
      console.log("this.temporaryResponse.data.data", this.temporaryResponse.data.data)
      const {
        taskTypeProblem,        // 任务类型匹配问题
        collisionRiskProblem,   // 碰撞风险问题
        airspaceSpacingProblem, // 空域间距问题
        timeConflictProblem,     // 时间冲突问题
        rejectReason,           // 后端返回的建议
      } = this.temporaryResponse.data.data;

      // 生成带颜色的HTML片段，确保颜色类正确应用
      const taskMatchHtml = `
        <p class="analysis-paragraph">
          1. <strong>任务类型匹配</strong>：
          <span class="${taskTypeProblem ? 'analysis-failed' : 'analysis-success'}">
            ${taskTypeProblem ? '存在类型不匹配问题，需确认任务类型与空域使用权限是否一致' : '未检测到类型冲突，任务类型与空域使用需求匹配正常'}
          </span>
        </p>
      `;

      const collisionRiskHtml = `
        <p class="analysis-paragraph">
          2. <strong>碰撞风险评估</strong>：
          <span class="${collisionRiskProblem ? 'analysis-failed' : 'analysis-success'}">
            ${collisionRiskProblem ? '存在碰撞风险隐患，空域范围内存在其他飞行任务重叠' : '未检测到碰撞风险，空域内飞行路径无交叉，安全可控'}
          </span>
        </p>
      `;

      const airspaceGapHtml = `
        <p class="analysis-paragraph">
          3. <strong>空域间距评估</strong>：
          <span class="${airspaceSpacingProblem ? 'analysis-failed' : 'analysis-success'}">
            ${airspaceSpacingProblem ? '存在空域间距不足问题，不符合安全间隔标准' : '空域间距符合《空域使用规范》要求，满足最小安全间隔'}
          </span>
        </p>
      `;

      const timeConflictHtml = `
        <p class="analysis-paragraph">
          4. <strong>时间冲突评估</strong>：
          <span class="${timeConflictProblem ? 'analysis-failed' : 'analysis-success'}">
            ${timeConflictProblem ? '存在时间重叠冲突，申请时段已被其他任务占用' : '未检测到时间冲突，申请的任务时段空闲可用'}
          </span>
        </p>
      `;

      // 🔥 核心修改：区分rejectReason是否为null
      // 定义默认建议文本（无论是否有rejectReason都需要的部分）
      const defaultSuggestion = '请根据上述分析结果，确认是否接收该空域申请；若存在失败项，需先协调解决对应问题。';

      // 拼接内容：有rejectReason则加上，否则只显示默认文本
      const suggestionContent = rejectReason != null && rejectReason.trim() !== ''
        ? `${rejectReason} ${defaultSuggestion}`  // 有值时拼接
        : defaultSuggestion;  // 为null或空时只显示默认文本

      // 始终生成处理建议段落（不再为空）
      const suggestionHtml = `
        <p class="analysis-suggestion">
          <strong>处理建议</strong>：${suggestionContent}
        </p>
      `;

      return taskMatchHtml + collisionRiskHtml + airspaceGapHtml + timeConflictHtml + suggestionHtml;
    }
  },
  mounted() {
    console.log('dialogData:', this.dialogData); // 在组件加载时打印dialogData
    console.log('module1组件右弹窗拿到的viewer', this.viewer)
    this.taskMatchStatus = 'pending';
    this.collisionRiskStatus = 'pending';
    this.airspaceGapStatus = 'pending';
    this.timeConflictStatus = 'pending';
  },
  beforeDestroy() {
    console.log("module1右侧弹窗组件销毁，开始清除GIS实体");
    this.clearCurrentDrawEntities();
  },
  watch: {
    title: {
      immediate: true,
      handler(newVal) {
        console.log('title changed:', newVal);
        if (newVal) {
          this.fetchData(newVal);  // 调用fetchData，传入id
        }
      }
    },
    temporaryResponse(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.taskMatchStatus = 'pending';
        this.collisionRiskStatus = 'pending';
        this.airspaceGapStatus = 'pending';
        this.timeConflictStatus = 'pending';

        this.showAnalysisResults = false;
      }
    }
  },
  methods: {
    DrawTrajectory() {
      try {
        this.clearCurrentDrawEntities(); // ✅ 放在最前面
        const { circular, polygonal, straight, sectorial } = this.tableData;
        const entitiesToFlyTo = [];
        // 存储当前的经纬度标签实体
        let currentLabelEntity = null;

        console.log("this.form.takeoffLocationCoordinates", this.form.takeoffLocationCoordinates)
        console.log("this.form.landingLocationCoordinates", this.form.landingLocationCoordinates)
        // 转换起飞和降落机场的坐标，并绘制圆柱体
        if (this.form.takeoffLocationCoordinates) {
          const [takeoffLon, takeoffLat] = this.parseCoordinates(this.form.takeoffLocationCoordinates);
          const takeoffEntity = drawCylinderAreaM1(
            this.viewer,
            takeoffLon,
            takeoffLat,
            0,
            50,
            50,
            'RED',
            0.5,
            '起飞机场'
          );
          entitiesToFlyTo.push(takeoffEntity);
          this.currentDrawEntities.push(takeoffEntity); // ✅ 新增
        }

        if (this.form.landingLocationCoordinates) {
          const [landingLon, landingLat] = this.parseCoordinates(this.form.landingLocationCoordinates);
          const landingEntity = drawCylinderAreaM1(
            this.viewer,
            landingLon,
            landingLat,
            0,
            50,
            50,
            'GREEN',
            0.5,
            '降落机场'
          );
          entitiesToFlyTo.push(landingEntity);
          this.currentDrawEntities.push(landingEntity); // ✅ 新增
        }
        // 绘制圆柱体轨迹（如果有的话）
        if (circular && circular.length > 0) {
          circular.forEach((coord, index) => {
            const entity = drawCylinderAreaM1(
              this.viewer,
              coord.longitude,
              coord.latitude,
              coord.minAltitude,
              coord.maxAltitude,
              coord.radius,
              'GREEN',
              0.5,
              '圆柱形区域'
            );
            if (entity) {
              this.tableData.circular[index].entity = entity;
              entitiesToFlyTo.push(entity);
              this.currentDrawEntities.push(entity); // ✅ 新增
            }
          });
        }

        // 绘制扇形柱体轨迹（如果有的话）
        if (sectorial && sectorial.length > 0) {
          console.log("绘制gis时的sectorial", sectorial)
          sectorial.forEach((coord, index) => {
            const entity = drawSectorCylinder(
              this.viewer,
              coord.longitude,
              coord.latitude,
              coord.minAltitude,
              coord.maxAltitude,
              coord.rin,
              coord.rout,
              coord.angleStart,
              coord.angle,
              'RED',
              0.5
            );
            if (entity) {
              this.tableData.sectorial[index].entity = entity;
              entitiesToFlyTo.push(entity);
              this.currentDrawEntities.push(entity); // ✅ 新增
            }
          });
        }

        // 绘制多边形柱状体轨迹
        if (polygonal && polygonal.length > 0) {
          console.log("绘制多边形柱状体传入的数据", polygonal)
          polygonal.forEach((track, index) => {
            const entity = draw3DPolygonalPrismM1(
              this.viewer,
              track.coordinates.map(coord => [coord.longitude, coord.latitude]).flat(),
              track.minAltitude,
              track.maxAltitude,
              'BLUE',
              0.5,
              '多边形区域',
              track.pointNames  // 传递点名
            );
            if (entity) {
              this.tableData.polygonal[index].entity = entity;
              entitiesToFlyTo.push(entity);
              this.currentDrawEntities.push(entity); // ✅ 新增
            }
          });
        }

        // 绘制长方体管道轨迹（如果有的话）
        if (straight && straight.length > 0) {
          console.log("绘制长方体管道传入的数据", straight);
          straight.forEach((track, index) => {
            const coordinates = track.coordinates.map(coord => [coord.longitude, coord.latitude, coord.altitude]).flat();
            const pointNames = track.urlStrings; // 获取每个轨迹点的名字

            // Ensure sizes array has the correct length
            const sizes = new Array(coordinates.length / 3 - 1).fill([100, 50]); // 对应生成每段长宽

            // Check if sizes length matches coordinates length - 1
            if (sizes.length !== coordinates.length / 3 - 1) {
              console.error('Sizes array length does not match coordinates array length minus one');
            } else {
              const entities = draw3DRectangularPipelineTrackM1_2(
                this.viewer,
                coordinates,
                sizes,
                0.5,
                'YELLOW',
                '需求航线区域',
              );
              if (entities) {
                this.tableData.straight[index].entity = entities;
                entitiesToFlyTo.push(...entities);
                this.currentDrawEntities.push(...entities); // ✅ 新增
              }
            }
          });
        }
        console.log("本组件绘制的GIS数据为", this.currentDrawEntities)

        // 如果有实体被绘制，飞行到这些实体的视角
        if (entitiesToFlyTo.length > 0) {
          this.viewer.flyTo(entitiesToFlyTo, {
            duration: 2,
            offset: {
              heading: Cesium.Math.toRadians(0),
              pitch: Cesium.Math.toRadians(-30),  // 视角抬高一些
              roll: 0
            }
          });
        }
      } catch (error) {
        console.error('绘制航迹时发生错误:', error);
      }
    },
    // 清除本组件绘制的GIS数据
    clearCurrentDrawEntities() {
      if (this.currentDrawEntities.length > 0) {
        this.currentDrawEntities.forEach(entity => {
          if (this.viewer.entities.contains(entity)) {
            this.viewer.entities.remove(entity);
          }
        });
        this.currentDrawEntities = []; // ✅ 清空记录
        console.log("执行完清除本组件函数后的本组件保存的GIS数据", this.currentDrawEntities)
      }
    },
    openAnalyzeDialog() {
      this.analyzing = true;
      this.rejectDialogVisible = true;
      console.log("此时的两个状态:", this.weatherStatus, this.airspaceStatus)
      setTimeout(() => {
        // 模拟分析过程完成
        this.weatherStatus = this.weatherStatus;
        this.airspaceStatus = this.airspaceStatus;
        this.analyzing = false;
      }, 2000); // 可替换为真实后端分析请求
    },
    dmsToDecimal(dms) {
      const [degrees, minutes, seconds] = dms.split(/[^\d\w.]+/).map(Number);
      return degrees + (minutes / 60) + (seconds / 3600);
    },

    parseCoordinates(coordString) {
      const [lonDMS, latDMS] = coordString.split(',').map(s => s.trim());
      const lon = this.dmsToDecimal(lonDMS);
      const lat = this.dmsToDecimal(latDMS);
      return [lon, lat];
    },
    focusOnTrajectory(type, row) {
      const entity = row.entity;

      if (entity && this.viewer) {
        this.viewer.flyTo(entity, {
          duration: 2,
          offset: {
            heading: Cesium.Math.toRadians(0),
            pitch: Cesium.Math.toRadians(-45),
            roll: 0
          }
        });
      }
    },
    destroyCesium() {
      // 在切换离开 'airspaceDemand' 时销毁 Cesium 实例
      if (this.viewer) {
        this.viewer.destroy();
        this.viewer = null;
      }
    },
    // // 初始化时向后端发送请求，获取数据
    // async fetchData(title) {
    //   try {
    //     // 使用 POST 请求并将 id 作为查询参数附加到 URL
    //     console.log("给后端发送的文件名信息", title)
    //     const stringTitle = title.toString()
    //     this.stringTitle = stringTitle
    //     console.log("给后端发送的文件名string信息", stringTitle)
    //     const response = await axios.post(`${baseApi}/admin/airspaceDemand/getById`, null, {
    //       params: {
    //         applicationId: stringTitle
    //       }
    //     });

    //     // 打印从接口获取的数据
    //     console.log('接口返回的数据:', response.data);
    //     this.temporaryResponse = response
    //     console.log("拿到接口返回的数据后就暂存", this.temporaryResponse)

    //     const data = response.data.data;

    //     // ✅ 缓存驳回弹窗所需数据（提前准备）
    //     const reasons = [];
    //     if (data.adjustUsingStartTime && data.adjustUsingEndTime) {
    //       reasons.push('空域使用时间冲突');
    //       this.cachedTimeRange = [data.adjustUsingStartTime, data.adjustUsingEndTime];
    //     }
    //     if (data.adjustUsingAirspace) {
    //       reasons.push('空域使用空间冲突');
    //       this.cachedAirspaceAdvice = data.adjustUsingAirspace;
    //     }
    //     this.cachedRejectReasons = reasons;

    //     // 将接口返回的数据一一对应赋值给form
    //     this.form = {
    //       applicationTime: response.data.data.applicationReceiveTime,
    //       applicant: response.data.data.applicantOrganization,
    //       contacts: response.data.data.contacts,
    //       telephone: response.data.data.telephone,
    //       aircraftManufacturer: response.data.data.aircraftManufacturer,
    //       aircraftModel: response.data.data.aircraftModel,
    //       aircraftType: response.data.data.aircraftType,
    //       aircraftControlType: response.data.data.aircraftControlType,
    //       maximumTakeoffWeight: response.data.data.maximumTakeoffWeight,
    //       dimensionsOfAircraftInDeployedState: response.data.data.aircraftDeployedSize,
    //       maximumFlightAltitude: response.data.data.maximumFlightAltitude,
    //       taskType: response.data.data.taskType,
    //       minimumFlightAltitude: response.data.data.minimumFlightAltitude,
    //       // taskStartTime: this.formatTaskTime(response.data.data.taskStartTime),
    //       // taskStartTime: this.formatTaskTime(
    //       //   response.data.data.taskStartTime && response.data.data.taskStartTime.length === 5
    //       //     ? new Date(
    //       //       response.data.data.taskStartTime[0], // 年
    //       //       response.data.data.taskStartTime[1] - 1, // 月（数组中的月从0开始）
    //       //       response.data.data.taskStartTime[2], // 日
    //       //       response.data.data.taskStartTime[3], // 时
    //       //       response.data.data.taskStartTime[4]  // 分
    //       //     )
    //       //     : null
    //       // ),
    //       taskStartTime: this.formatTaskTime(
    //         response.data.data.taskStartTime ? new Date(response.data.data.taskStartTime) : null
    //       ),
    //       isRoundTrip: response.data.data.isRoundTrip,
    //       // taskEndTime: this.formatTaskTime(response.data.data.taskEndTime),
    //       // taskEndTime: this.formatTaskTime(
    //       //   response.data.data.taskEndTime && response.data.data.taskEndTime.length === 5
    //       //     ? new Date(
    //       //       response.data.data.taskEndTime[0], // 年
    //       //       response.data.data.taskEndTime[1] - 1, // 月（数组中的月从0开始）
    //       //       response.data.data.taskEndTime[2], // 日
    //       //       response.data.data.taskEndTime[3], // 时
    //       //       response.data.data.taskEndTime[4]  // 分
    //       //     )
    //       //     : null
    //       // ),
    //       taskEndTime: this.formatTaskTime(
    //         response.data.data.taskEndTime ? new Date(response.data.data.taskEndTime) : null
    //       ),
    //       flightFrequency: response.data.data.flightFrequency,
    //       takeoffLocationName: response.data.data.vertiportTOName,
    //       takeoffLocationCode: response.data.data.vertiportTOCode,
    //       takeoffLocationType: response.data.data.vertiportTOType,
    //       // takeoffLocationCoordinates: `${this.formatCoordinate(response.data.data.takeoffLocationCoordinates.longitude)}, ${this.formatCoordinate(response.data.data.takeoffLocationCoordinates.latitude)}`,
    //       takeoffLocationCoordinates: response?.data?.data?.takeoffLocationCoordinates?.longitude != null && response?.data?.data?.takeoffLocationCoordinates?.latitude != null
    //         ? `${this.formatCoordinate(response.data.data.takeoffLocationCoordinates.longitude)}, ${this.formatCoordinate(response.data.data.takeoffLocationCoordinates.latitude)}`
    //         : '未知位置',
    //       landingLocationName: response.data.data.vertiportLDName,
    //       landingLocationCode: response.data.data.vertiportLDCode,
    //       landingLocationType: response.data.data.vertiportLDType,
    //       // landingLocationCoordinates: `${this.formatCoordinate(response.data.data.landingLocationCoordinates.longitude)}, ${this.formatCoordinate(response.data.data.landingLocationCoordinates.latitude)}`,
    //       landingLocationCoordinates: response?.data?.data?.landingLocationCoordinates?.longitude != null && response?.data?.data?.landingLocationCoordinates?.latitude != null
    //         ? `${this.formatCoordinate(response.data.data.landingLocationCoordinates.longitude)}, ${this.formatCoordinate(response.data.data.landingLocationCoordinates.latitude)}`
    //         : '未知位置',
    //       id: response.data.data.id,
    //       userName: response.data.data.userName,
    //       applicationAcceptanceTime: response.data.data.applicationAcceptanceTime,
    //       applicationId: response.data.data.applicationId,
    //       approvalStatus: response.data.data.approvalStatus,
    //       airspaceType: response.data.data.airspaceType,
    //       circularAirspace: response.data.data.circularAirspace,
    //       polygonalAirspace: response.data.data.polygonalAirspace,
    //       straightAirspace: response.data.data.straightAirspace,
    //       // circleCenterCoordinates: `${response.data.data.circleCenterCoordinates.longitude}, ${response.data.data.circleCenterCoordinates.latitude}`,
    //       circleCenterCoordinates: response?.data?.data?.circleCenterCoordinates?.longitude != null && response?.data?.data?.circleCenterCoordinates?.latitude != null
    //         ? `${response.data.data.circleCenterCoordinates.longitude}, ${response.data.data.circleCenterCoordinates.latitude}`
    //         : '未知位置',
    //       radius: response.data.data.radius,
    //     };

    //     // 根据 flyTimesUnit 设置频次单位
    //     this.frequencyUnit = response.data.data.flyTimesUnit === 1 ? '次/周' : '次/天';  // 如果是1，则是次/周，否则是次/天

    //     // 处理 tableData
    //     this.tableData = {
    //       circular: [],
    //       polygonal: [],
    //       straight: [],
    //       sectorial: []
    //     };

    //     // 如果圆形轨迹存在，添加相应的数据
    //     if (response.data.data.circleCenterCoordinates && response.data.data.circleCenterCoordinates.length > 0) {
    //       response.data.data.circleCenterCoordinates.forEach((coord, index) => {
    //         if (coord && coord.longitude !== undefined && coord.latitude !== undefined) {
    //           if (coord.radius) {
    //             // 圆柱体数据
    //             this.tableData.circular.push({
    //               wayId: index + 1, // 生成的 wayId，基于索引
    //               longitude: coord.longitude,
    //               latitude: coord.latitude,
    //               minAltitude: coord.minAltitude,
    //               maxAltitude: coord.maxAltitude,
    //               radius: coord.radius,
    //               pointName: `Circle Center`  // 为圆心命名
    //             });
    //           } else {
    //             // 扇形柱体数据
    //             this.tableData.sectorial = this.tableData.sectorial || []; // 如果不存在扇形数据数组，先初始化
    //             this.tableData.sectorial.push({
    //               wayId: index + 1, // 生成的 wayId，基于索引
    //               longitude: coord.longitude,
    //               latitude: coord.latitude,
    //               minAltitude: coord.minAltitude,
    //               maxAltitude: coord.maxAltitude,
    //               rin: coord.rin,
    //               rout: coord.rout,
    //               angleStart: coord.angleStart,
    //               angle: coord.angle,
    //               pointName: `Sector Center`  // 为扇形中心命名
    //             });
    //             console.log("存入时的扇形主题数据tableData.sectorial", this.tableData.sectorial)
    //           }
    //         } else {
    //           console.warn("Missing or invalid data for circle center coordinate:", coord);
    //         }
    //       });
    //     }

    //     // 如果多边形轨迹存在，按 wayId 进行分类
    //     if (response.data.data.polygonalWaypointsCoordinates && response.data.data.polygonalWaypointsCoordinates.length > 0) {
    //       const groupedPolygonal = {};

    //       response.data.data.polygonalWaypointsCoordinates.forEach(point => {
    //         if (point && point.id !== undefined && point.longitude !== undefined && point.latitude !== undefined) {
    //           const wayId = point.id;
    //           if (!groupedPolygonal[wayId]) {
    //             groupedPolygonal[wayId] = {
    //               pointNames: [],
    //               minAltitude: point.minAltitude,
    //               maxAltitude: point.maxAltitude,
    //               coordinates: []
    //             };
    //           }
    //           const pointName = `URZ${wayId}-${point.pointId}`;
    //           groupedPolygonal[wayId].pointNames.push(pointName);

    //           groupedPolygonal[wayId].coordinates.push({
    //             longitude: point.longitude,
    //             latitude: point.latitude
    //           });
    //         } else {
    //           console.warn("Missing or invalid data for point:", point);
    //         }
    //       });

    //       this.tableData.polygonal = Object.keys(groupedPolygonal).map(wayId => ({
    //         wayId: wayId,
    //         pointNames: groupedPolygonal[wayId].pointNames,
    //         minAltitude: groupedPolygonal[wayId].minAltitude,
    //         maxAltitude: groupedPolygonal[wayId].maxAltitude,
    //         coordinates: groupedPolygonal[wayId].coordinates
    //       }));
    //     }

    //     // 如果线形轨迹存在，按 wayId 进行分类
    //     if (response.data.data.straightWaypointsCoordinates && response.data.data.straightWaypointsCoordinates.length > 0) {
    //       const groupedStraight = {};

    //       response.data.data.straightWaypointsCoordinates.forEach(point => {
    //         const wayId = point.id;
    //         if (!groupedStraight[wayId]) {
    //           groupedStraight[wayId] = {
    //             urlStrings: [],
    //             coordinates: []
    //           };
    //         }
    //         const urlString = `URL${wayId}-${point.pointId}`;
    //         groupedStraight[wayId].urlStrings.push(urlString);

    //         groupedStraight[wayId].coordinates.push({
    //           longitude: point.longitude,
    //           latitude: point.latitude,
    //           altitude: point.altitude
    //         });
    //       });

    //       this.tableData.straight = Object.keys(groupedStraight).map(wayId => ({
    //         wayId: wayId,
    //         urlStrings: groupedStraight[wayId].urlStrings,
    //         coordinates: groupedStraight[wayId].coordinates
    //       }));
    //     }

    //     console.log("更新后的form", this.form);
    //     console.log("更新后的tableData", this.tableData);
    //     // 调用绘制
    //     this.DrawTrajectory();
    //   } catch (error) {
    //     console.error('请求接口时发生错误:', error);
    //   }
    // },
    // 初始化时向后端发送请求：先调老接口拿基础信息，再调新接口补空域数据
    async fetchData(title) { // 保留老接口需要的title参数
      try {
        // -------------------------- 1. 先调用老接口：获取基础信息 --------------------------
        console.log("给老接口发送的文件名信息", title);
        const stringTitle = title.toString();
        this.stringTitle = stringTitle;
        console.log("给老接口发送的文件名string信息", stringTitle);

        // 老接口请求（URL、参数不变，保留原有逻辑）
        const oldApiResponse = await axios.post(`${baseApi}/admin/airspaceDemand/getById`, null, {
          params: {
            applicationId: stringTitle // 老接口必需的applicationId参数
          }
        });

        console.log('老接口返回的基础数据:', oldApiResponse.data);
        this.temporaryResponse = oldApiResponse; // 暂存老接口数据（兼容原逻辑）

        // 提取老接口的核心数据作为基础（后续将新接口的空域数据合并到这里）
        let mergedData = oldApiResponse.data.data;
        // 初始化老接口中可能缺失的空域字段（避免合并时undefined）
        mergedData = {
          ...mergedData,
          circularAirspace: 0,    // 初始设为0（无圆形空域）
          polygonalAirspace: 0,   // 初始设为0（无多边形空域）
          straightAirspace: 0,    // 初始设为0（无线形空域）
          circleCenterCoordinates: [],       // 新接口补充：起降站（圆柱体）坐标
          straightWaypointsCoordinates: [],  // 新接口补充：航路（线形）坐标
          polygonalWaypointsCoordinates: []  // 新接口补充：作业区（多边形）坐标
        };


        // -------------------------- 2. 再调用新接口：补充空域绘制数据 --------------------------
        console.log("给新接口发送的测试id：2");
        const newApiResponse = await axios.post(`${baseApi}/admin/airspaceDemand/getObjectById`, null, {
          params: {
            id: 2 // 新接口必需的Query参数（测试用固定值，后续替换为实际变量）
          }
        });

        console.log('新接口返回的空域数据:', newApiResponse.data);
        const newDataList = newApiResponse.data.data; // 新接口的data数组


        // -------------------------- 3. 核心：合并新接口的空域数据到老数据中 --------------------------
        newDataList.forEach(item => {
          const { type: itemType, shapes, name: itemName } = item;
          if (itemType === 0) return; // 忽略老数据，只处理type=1/2/3

          // 遍历每个shape，提取坐标和空域信息
          shapes.forEach(shape => {
            const {
              id: shapeId,
              minAltitude,
              maxAltitude,
              rout: radius, // 新接口中rout对应老接口的“半径”
              points
            } = shape;

            // 按新接口的type分类，补充到mergedData对应的空域字段中
            points.forEach(point => {
              const { longitude, latitude, altitude, sequence: pointId } = point;
              const coordinateItem = {
                longitude,
                latitude,
                altitude,
                minAltitude,
                maxAltitude,
                radius: radius || 0 // 圆形空域的半径（仅type=1有用）
              };

              switch (itemType) {
                // 👉 type=1：起降站（圆柱体）→ 补充到circleCenterCoordinates
                case 1:
                  mergedData.circleCenterCoordinates.push({
                    ...coordinateItem,
                    // 补充老接口circleCenterCoordinates可能需要的字段（如rin/rout，按需调整）
                    rin: shape.rin || 0,
                    rout: shape.rout || 0,
                    angleStart: shape.angleStart || 0,
                    angle: shape.angle || 0
                  });
                  // 更新空域状态：有数据则设为1（表示“有圆形空域”）
                  mergedData.circularAirspace = 1;
                  // 可选：用新接口的起降站名称补充老接口的vertiportTOName（若老接口缺失）
                  if (!mergedData.vertiportTOName) {
                    mergedData.vertiportTOName = itemName || '起降站';
                    mergedData.vertiportTOCode = `VERT-${shapeId}`;
                  }
                  break;

                // 👉 type=2：航路（线形）→ 补充到straightWaypointsCoordinates
                case 2:
                  mergedData.straightWaypointsCoordinates.push({
                    id: shapeId,       // 老接口需要的wayId（用新接口shape的id）
                    pointId: pointId,  // 老接口需要的pointId（用新接口point的sequence）
                    ...coordinateItem
                  });
                  // 更新空域状态：有数据则设为1（表示“有线性空域”）
                  mergedData.straightAirspace = 1;
                  break;

                // 👉 type=3：作业区（多边形）→ 补充到polygonalWaypointsCoordinates
                case 3:
                  mergedData.polygonalWaypointsCoordinates.push({
                    id: shapeId,       // 老接口需要的wayId（用新接口shape的id）
                    pointId: pointId,  // 老接口需要的pointId（用新接口point的sequence）
                    ...coordinateItem
                  });
                  // 更新空域状态：有数据则设为1（表示“有多边形空域”）
                  mergedData.polygonalAirspace = 1;
                  break;

                default:
                  break;
              }
            });
          });
        });


        // -------------------------- 4. 后续逻辑完全复用原有代码（用合并后的mergedData） --------------------------
        const data = mergedData; // 此时data = 老接口基础信息 + 新接口空域数据

        // ✅ 缓存驳回弹窗所需数据（逻辑不变，依赖老接口的adjustUsingStartTime等字段）
        const reasons = [];
        if (data.adjustUsingStartTime && data.adjustUsingEndTime) {
          reasons.push('空域使用时间冲突');
          this.cachedTimeRange = [data.adjustUsingStartTime, data.adjustUsingEndTime];
        }
        if (data.adjustUsingAirspace) {
          reasons.push('空域使用空间冲突');
          this.cachedAirspaceAdvice = data.adjustUsingAirspace;
        }
        this.cachedRejectReasons = reasons;

        // 将合并后的数据赋值给form（完全复用原逻辑，基础字段来自老接口，空域字段来自新接口）
        this.form = {
          applicationTime: data.applicationReceiveTime,
          applicant: data.applicantOrganization,
          contacts: data.contacts,
          telephone: data.telephone,
          aircraftManufacturer: data.aircraftManufacturer,
          aircraftModel: data.aircraftModel,
          aircraftType: data.aircraftType,
          aircraftControlType: data.aircraftControlType,
          maximumTakeoffWeight: data.maximumTakeoffWeight,
          dimensionsOfAircraftInDeployedState: data.aircraftDeployedSize,
          maximumFlightAltitude: data.maximumFlightAltitude,
          minimumFlightAltitude: data.minimumFlightAltitude,
          taskType: data.taskType,
          taskStartTime: this.formatTaskTime(data.taskStartTime ? new Date(data.taskStartTime) : null),
          isRoundTrip: data.isRoundTrip,
          taskEndTime: this.formatTaskTime(data.taskEndTime ? new Date(data.taskEndTime) : null),
          flightFrequency: data.flightFrequency,
          takeoffLocationName: data.vertiportTOName,
          takeoffLocationCode: data.vertiportTOCode,
          takeoffLocationType: data.vertiportTOType,
          takeoffLocationCoordinates: data.takeoffLocationCoordinates?.longitude != null && data.takeoffLocationCoordinates?.latitude != null
            ? `${this.formatCoordinate(data.takeoffLocationCoordinates.longitude)}, ${this.formatCoordinate(data.takeoffLocationCoordinates.latitude)}`
            : '未知位置',
          landingLocationName: data.vertiportLDName,
          landingLocationCode: data.vertiportLDCode,
          landingLocationType: data.vertiportLDType,
          landingLocationCoordinates: data.landingLocationCoordinates?.longitude != null && data.landingLocationCoordinates?.latitude != null
            ? `${this.formatCoordinate(data.landingLocationCoordinates.longitude)}, ${this.formatCoordinate(data.landingLocationCoordinates.latitude)}`
            : '未知位置',
          id: data.id,
          userName: data.userName,
          applicationAcceptanceTime: data.applicationAcceptanceTime,
          applicationId: data.applicationId,
          approvalStatus: data.approvalStatus,
          airspaceType: data.airspaceType,
          circularAirspace: data.circularAirspace, // 来自新接口合并后的数据
          polygonalAirspace: data.polygonalAirspace, // 来自新接口合并后的数据
          straightAirspace: data.straightAirspace, // 来自新接口合并后的数据
          circleCenterCoordinates: data.circleCenterCoordinates.length > 0
            ? `${data.circleCenterCoordinates[0].longitude}, ${data.circleCenterCoordinates[0].latitude}`
            : '未知位置',
          radius: data.radius || (data.circleCenterCoordinates[0]?.radius || 0) // 来自新接口的radius
        };

        // 根据老接口的flyTimesUnit设置频次单位（逻辑不变）
        this.frequencyUnit = data.flyTimesUnit === 1 ? '次/周' : '次/天';

        // 处理tableData（完全复用原逻辑，空域坐标来自新接口合并后的数据）
        this.tableData = {
          circular: [],
          polygonal: [],
          straight: [],
          sectorial: []
        };

        // 处理圆形/扇形轨迹（复用原逻辑，数据来自新接口）
        if (data.circleCenterCoordinates && data.circleCenterCoordinates.length > 0) {
          data.circleCenterCoordinates.forEach((coord, index) => {
            if (coord && coord.longitude !== undefined && coord.latitude !== undefined) {
              if (coord.radius) {
                this.tableData.circular.push({
                  wayId: index + 1,
                  longitude: coord.longitude,
                  latitude: coord.latitude,
                  minAltitude: coord.minAltitude,
                  maxAltitude: coord.maxAltitude,
                  radius: coord.radius,
                  pointName: `Circle Center`
                });
              } else {
                this.tableData.sectorial = this.tableData.sectorial || [];
                this.tableData.sectorial.push({
                  wayId: index + 1,
                  longitude: coord.longitude,
                  latitude: coord.latitude,
                  minAltitude: coord.minAltitude,
                  maxAltitude: coord.maxAltitude,
                  rin: coord.rin,
                  rout: coord.rout,
                  angleStart: coord.angleStart,
                  angle: coord.angle,
                  pointName: `Sector Center`
                });
              }
            } else {
              console.warn("Missing or invalid data for circle center coordinate:", coord);
            }
          });
        }

        // 处理多边形轨迹（使用前端生成的连续序号，从1开始）
        if (data.polygonalWaypointsCoordinates && data.polygonalWaypointsCoordinates.length > 0) {
          // 1. 先按后端原始id分组（保留原始分组逻辑）
          const groupedPolygonal = {};
          data.polygonalWaypointsCoordinates.forEach(point => {
            if (point && point.id !== undefined && point.longitude !== undefined && point.latitude !== undefined) {
              const originalWayId = point.id; // 后端原始id（仅用于临时分组）
              if (!groupedPolygonal[originalWayId]) {
                groupedPolygonal[originalWayId] = {
                  pointNames: [],
                  minAltitude: point.minAltitude,
                  maxAltitude: point.maxAltitude,
                  coordinates: []
                };
              }
              // 临时使用原始id生成名称（后续会替换）
              groupedPolygonal[originalWayId].pointNames.push(`URZ_TEMP-${originalWayId}-${point.pointId}`);
              groupedPolygonal[originalWayId].coordinates.push({
                longitude: point.longitude,
                latitude: point.latitude
              });
            } else {
              console.warn("Missing or invalid data for point:", point);
            }
          });

          // 2. 转换为前端连续序号（从1开始）
          const originalWayIds = Object.keys(groupedPolygonal); // 后端原始id列表
          this.tableData.polygonal = originalWayIds.map((originalWayId, index) => {
            const newWayId = index + 1; // 前端新序号（1,2,3...）
            const group = groupedPolygonal[originalWayId];
            // 替换pointNames中的临时编号为新序号
            const newPointNames = group.pointNames.map(name => {
              // 正则替换原始id为新序号（例如 URZ_TEMP-273-1 → URZ1-1）
              return name.replace(/URZ_TEMP-\d+-(\d+)/, `URZ${newWayId}-$1`);
            });
            return {
              wayId: newWayId, // 前端显示的序号
              pointNames: newPointNames,
              minAltitude: group.minAltitude,
              maxAltitude: group.maxAltitude,
              coordinates: group.coordinates
            };
          });
        }

        // 处理线形轨迹（使用前端生成的连续序号，从1开始）
        if (data.straightWaypointsCoordinates && data.straightWaypointsCoordinates.length > 0) {
          // 1. 先按后端原始id分组（保留原始分组逻辑）
          const groupedStraight = {};
          data.straightWaypointsCoordinates.forEach(point => {
            const originalWayId = point.id; // 后端原始id（仅用于临时分组）
            if (!groupedStraight[originalWayId]) {
              groupedStraight[originalWayId] = {
                urlStrings: [],
                coordinates: []
              };
            }
            // 临时使用原始id生成名称（后续会替换）
            groupedStraight[originalWayId].urlStrings.push(`URL_TEMP-${originalWayId}-${point.pointId}`);
            groupedStraight[originalWayId].coordinates.push({
              longitude: point.longitude,
              latitude: point.latitude,
              altitude: point.altitude
            });
          });

          // 2. 转换为前端连续序号（从1开始）
          const originalWayIds = Object.keys(groupedStraight); // 后端原始id列表
          this.tableData.straight = originalWayIds.map((originalWayId, index) => {
            const newWayId = index + 1; // 前端新序号（1,2,3...）
            const group = groupedStraight[originalWayId];
            // 替换urlStrings中的临时编号为新序号
            const newUrlStrings = group.urlStrings.map(url => {
              // 正则替换原始id为新序号（例如 URL_TEMP-293-1 → URL1-1）
              return url.replace(/URL_TEMP-\d+-(\d+)/, `URL${newWayId}-$1`);
            });
            return {
              wayId: newWayId, // 前端显示的序号
              urlStrings: newUrlStrings,
              coordinates: group.coordinates
            };
          });
        }

        console.log("合并后的数据（老接口基础信息+新接口空域数据）:", data);
        console.log("更新后的form", this.form);
        console.log("更新后的tableData", this.tableData);
        // 调用绘制（原逻辑不变，数据已补充完整）
        this.DrawTrajectory();

      } catch (error) {
        console.error('请求接口时发生错误:', error);
        // 可选：区分老接口/新接口的错误（便于调试）
        if (error.config.url.includes('getById')) {
          console.error('老接口请求失败:', error);
        } else if (error.config.url.includes('getObjectById')) {
          console.error('新接口请求失败:', error);
        }
      }
    },
    // 处理分析按钮点击
    async handleAnalyze() {
      this.analyzing = true; // 开始分析，显示加载状态
      this.showAnalysisResults = true;

      // 全部先标记为 analyzing 状态
      this.taskMatchStatus = 'analyzing';
      this.collisionRiskStatus = 'analyzing';
      this.airspaceGapStatus = 'analyzing';
      this.timeConflictStatus = 'analyzing';
      try {
        // 模拟整体分析延迟
        await new Promise(resolve => setTimeout(resolve, 1000));

        // 开始逐个更新分析结果
        // 任务类型匹配
        if (this.temporaryResponse.data.data.taskTypeProblem) {
          this.taskMatchStatus = 'failed';
        } else {
          this.taskMatchStatus = 'success';
        }
        await new Promise(resolve => setTimeout(resolve, 500)); // 等 0.5 秒再出现下一个

        // 碰撞风险评估
        if (this.temporaryResponse.data.data.collisionRiskProblem) {
          this.collisionRiskStatus = 'failed';
        } else {
          this.collisionRiskStatus = 'success';
        }
        await new Promise(resolve => setTimeout(resolve, 500));

        // 空域间距评估
        if (this.temporaryResponse.data.data.airspaceSpacingProblem) {
          this.airspaceGapStatus = 'failed';
        } else {
          this.airspaceGapStatus = 'success';
        }
        await new Promise(resolve => setTimeout(resolve, 500));

        // 时间冲突评估
        if (this.temporaryResponse.data.data.timeConflictProblem) {
          this.timeConflictStatus = 'failed';
        } else {
          this.timeConflictStatus = 'success';
        }

      } catch (error) {
        console.error('分析请求失败:', error);
        this.$message.error('分析失败，请重试');
        this.weatherStatus = 'failed';
        this.airspaceStatus = 'failed';
        // 出错时全部失败
        this.taskMatchStatus =
          this.collisionRiskStatus =
          this.airspaceGapStatus =
          this.timeConflictStatus = 'failed';
      } finally {
        // this.showAnalysisResults = true;
        this.analyzing = false; // 结束分析，关闭加载状态
      }
    },
    // 打开驳回弹窗逻辑
    async prepareReject() {
      this.rejectInitReasons = this.cachedRejectReasons;
      this.rejectInitTimeRange = this.cachedTimeRange;
      this.rejectInitAirspaceAdvice = this.cachedAirspaceAdvice;

      this.rejectDialogVisible = true;
    },
    handleFinalReject(payload) {
      // 确保使用父组件的 title 作为正确的 applicationId
      payload.applicationId = this.title;
      console.log("🚀 驳回时正在提交的 payload:", payload);
      // 👇 发接口
      axios.post(`${baseApi}/admin/airspaceDemand/updateApprovalStatus`, payload)
        .then(res => {
          if (res.data.code === 0) {
            this.$message.success('已驳回');
          } else {
            this.$message.error(res.data.message || '驳回失败');
          }
        });
    },
    formatTimeRange(start, end) {
      if (!start || !end) return '';
      const s = this.$moment ? this.$moment(start).format('YYYY-MM-DD HH:mm') : new Date(start).toLocaleString();
      const e = this.$moment ? this.$moment(end).format('YYYY-MM-DD HH:mm') : new Date(end).toLocaleString();
      return `${s} ~ ${e}`;
    },
    // 转换经度、纬度的格式，转换成度分秒的形式
    formatCoordinate(coord) {
      const degrees = Math.floor(coord);
      const minutes = Math.floor((coord - degrees) * 60);
      const seconds = (((coord - degrees) * 60 - minutes) * 60).toFixed(1);
      return `${degrees}°${minutes}'${seconds}"`;
    },
    // 格式化任务开始时间，将异常格式转换为有效日期格式
    formatTaskTime(timeStr) {
      // 确保 timeStr 是一个有效的时间字符串
      const date = new Date(timeStr);
      console.log("拿到的时间数据初始版本", timeStr)
      // 检查是否是一个有效日期
      if (isNaN(date.getTime())) {
        return '';  // 如果日期无效，返回空字符串
      }

      // 格式化日期为 yyyy-MM-dd HH:mm:ss 格式
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');  // 补全为两位数
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    closeDialog() {
      this.$emit('update:visible', false);
    },
    handleAccept() {
      this.submitForm(1); // 调用已有逻辑，发送“接收”请求
    },
    // 提交表单的函数
    async submitForm(newApprovalStatus) {
      try {
        const id = this.form.id;  // 从表单中获取订单需求的 id
        const title = this.title
        console.log("文件名", title)
        const response = await axios.post(`${baseApi}/admin/airspaceDemand/updateApprovalStatus`, {
          applicationId: title,  // 订单需求的 id
          newApprovalStatus: newApprovalStatus  // 根据点击的按钮设置状态，同意为1，驳回为2
        });

        console.log('同意/驳回请求返回的数据:', response.data);
        if (response.data.code == 0) {
          this.$emit('update:visible', false);  // 成功后关闭弹窗
          this.$message.success('操作成功');
          this.$emit('status-updated'); // 通知父组件状态已更新
        } else {
          this.$message.error('操作失败');
        }
      } catch (error) {
        console.error('请求时发生错误:', error);
        this.$message.error('请求失败，请稍后再试');
      }
    },
  }
};
</script>

<style scoped>
.header-content-top {
  position: relative;
  width: 100%;
  /* 使其占据整个宽度 */
  height: 5%;
  background: url("../assets/img/module1/page1top.png") no-repeat;
  background-size: cover;
  display: flex;
  align-items: center;
  /* 垂直居中 */
  /* 增加内部间距 */
}

/* 标题样式 */
.header-title {
  background-image: linear-gradient(180deg,
      rgba(200, 215, 228, 1) 0,
      rgba(255, 255, 255, 1) 100%);
  position: relative;
  font-weight: 600;
  flex: 2;
  margin-left: 40px;
  width: 10%;
  height: 10%;
  color: rgba(112, 112, 112, 1);
  font-size: 20px;
  letter-spacing: 1px;
  font-family: PangMenZhengDao-3;
  text-align: left;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 图标样式 */
.header-icon {
  position: relative;
  width: 22px;
  height: 20px;
  margin-left: 20px;
  /* 与其他内容间隔 */
  margin-top: -20px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 7%;
  margin-top: 0.5%;
}

.header-left {
  display: flex;
}

.header-right {
  margin-right: 2vh;
  /* 右边的按钮和边界的间隔 */
}

.button {
  display: flex;
  background: url(../assets/img/module4/part1/SketchPng672f442656b7e0f3c9863869768a199363cee97583efcf5fc791168bad3b2f9f.png) no-repeat center center;
  background-size: contain;
  color: #ffffff;
  border: none;
  padding: 0.8vh 3vw 1.5vh 3vw;
  font-size: 1rem;

}

.button.active,
.button:hover {
  background: url(../assets/img/module4/part1/SketchPng09fb34004ea1b0e5e91ff03feafa38bcb15201eba65a4db7b12083a8412bcc68.png) no-repeat center center;
  background-size: contain;
  padding: 0.8vh 3vw 1.5vh 3vw;
}

.dialog_main {
  width: 100%;
  border-radius: 10px;
  padding: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  background-color: transparent;
  margin-top: 0.2rem;
  background-image: linear-gradient(rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.1)),
    url(/static/img/map.d85bf848.png);
}

.header-section {
  width: 100%;
  height: 5%;
  background: url('../assets/img/module1/dialog_top.png') no-repeat center center;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
}

.header-content {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.header-text {
  color: white;
  font-size: 1.2rem;
  font-weight: bold;
  text-align: center;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.body-section {
  flex-grow: 1;
  background: url('../assets/img/module1/bg_wai.png') no-repeat center center;
  background-size: cover;
  padding: 0.6rem 0.6rem 0.6rem 0.6rem;
  display: flex;
  flex-direction: column;
  border-radius: 0.5rem;
}

.subbody-2 {
  width: 100%;
  height: 100%;
  background: url('../assets/img/module1/bg_nei.png') no-repeat center center;
  background-size: cover;
  display: flex;
  border-radius: 0.5rem;
}

.subbody-3 {
  /* width: 95%; */
  width: 100%;
}

/* 左侧和右侧的样式 */
.subbody-content {
  /* height: 35vh; */
  display: flex;
  justify-content: space-between;
  padding: 0vh 0vw;
  overflow: auto;
  margin-bottom: 7rem;
}

.form-left,
.form-right {
  width: 45%;
}

.form-content {
  display: flex;
  flex-direction: column;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
  font-size: 18px;
  color: #fff;
}

.form-label {
  width: 10vw;
  font-weight: 400;
  color: #fff;
  text-align: right;
  margin-right: 1.3vw;
  font-size: 18px;
}

.form-input {
  /* flex: 1; */
  padding: 8px;
  box-sizing: border-box;
  border: 1px solid rgba(213, 218, 222, 0.09);
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.1);
  color: #fff;
  width: 280px;
  font-size: 18px;
  font-weight: 400;
  margin-right: 10px;
}

/* 空域使用需求部分 */
.airspace-demand-content {
  display: flex;
  justify-content: space-between;
  width: 100%;
  /* height: 52vh; */
  /* height: 90%; */
  overflow-y: auto;
  /* 超出时垂直滚动 */
  /* padding: 1.5vh; */
  padding: 1.5vh 1.5vh 0.5vh 1.5vh;
}

label {
  width: 10vw;
  font-weight: 400;
  color: #fff;
  text-align: right;
  margin-right: 1vw;
  font-size: 18px;
}

input {
  /* flex: 1; */
  padding: 8px;
  box-sizing: border-box;
  border: 1px solid rgba(213, 218, 222, 0.09);
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.1);
  color: #fff;
  width: 280px;
  font-size: 18px;
  font-weight: 400;
}

/* 隐藏滚动条 - Webkit浏览器（Chrome, Safari等） */
.airspace-demand-content::-webkit-scrollbar {
  width: 0;
  height: 0;
}

/* 隐藏滚动条 - Firefox */
.airspace-demand-content {
  scrollbar-width: none;
  /* Firefox 隐藏滚动条 */
}

/* 隐藏滚动条 - IE/Edge */
.airspace-demand-content {
  -ms-overflow-style: none;
  /* IE/Edge 隐藏滚动条 */
}

.image-content {
  width: 42%;
  height: 60vh;
  /* background-color: rgba(127, 255, 212, 0.141); */
  display: flex;
  flex-direction: column;
  /* 子元素垂直排列 */
  justify-content: center;
  align-items: center;
  /* transition: width 0.3s ease, height 0.3s ease; */
}

.image-content.fullscreen {
  width: 100%;
  height: 70vh;
}

.fullscreen-button {
  margin-top: 1rem;
  margin-bottom: 0.5rem;
  align-self: flex-end;
  /* 按钮靠左对齐 */
}

.fullscreen-active {
  margin-top: 0;
}

/* 自定义表单内容 */
.custom-form-content {
  width: 96%;
  display: flex;
  margin-top: 1rem;
  flex-direction: column;
  gap: 15px;
  max-height: 50vh;
}

.custom-form-row {
  display: flex;
  /* justify-content: space-between; */
  gap: 7rem;
}

.custom-form-item {
  display: flex;
  align-items: center;
  /* 上下居中 */
  justify-content: flex-start;
  /* 左对齐 */
}

.custom-form-item.full-width {
  width: 100%;
}

.custom-form-item label {
  width: 3vw;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
  text-align: right;
  margin-left: 1rem;
  white-space: nowrap;
  /* 防止文本换行 */
}

.custom-form-item input {
  flex: 1;
  padding: 6px 12px;
  width: 160px;
  background-color: rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(213, 218, 222, 0.09);
  border-radius: 4px;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
}

.custom-form-item-group {
  display: flex;
  gap: 0.5rem;
}

.custom-unit {
  margin-left: 5px;
  color: white;
}

.custom-form-row-new {
  display: flex;
  justify-content: space-between;
  gap: 0px;
  width: 100%;
}

.custom-form-item-new {
  /* flex: 1; */
  display: flex;
  align-items: center;
  min-width: 0;
}

.custom-form-item-new label {
  width: 6vw;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
  text-align: right;
  margin-right: 10px;
}

.custom-form-item-new input {
  /* flex: 1; */
  padding: 6px 12px;
  /* width: 180px; */
  background-color: rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(213, 218, 222, 0.09);
  border-radius: 4px;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
}

/* 空域类型提示框 */
.info-box-yhr-dialog-module1 {
  background-color: #2d2d2df1;
  color: white;
  border-radius: 4px;
  font-size: 1rem;
  width: 30%;
  margin-left: 1rem;
}

.regional_table {
  margin-left: 1rem;
  height: 50%;
  overflow-y: auto;
}

.regional_table::-webkit-scrollbar {
  width: 0.125rem;
  background-color: rgba(0, 16, 29, 0.5) !important;
}

.regional_table::-webkit-scrollbar-thumb {
  background: #0378FF;
  border-radius: 0.625rem;
}

/* 最外层透明表格背景与白色字体 */
.regional_table /deep/ .el-table,
.regional_table /deep/ .el-table__expanded-cell {
  background-color: transparent;
  /* 设置透明背景 */
  color: white;
  /* 表格文字颜色 */
}

/* 表格头部和单元格的背景颜色透明 */
.regional_table /deep/ .el-table th,
.regional_table /deep/ .el-table tr,
.regional_table /deep/ .el-table td {
  background-color: transparent !important;
  /* 背景透明 */
  color: white;
  /* 确保文字为白色 */
}

/* 设置表格边框 */
.regional_table /deep/ .el-table__body-wrapper {
  /* border: 1px solid white;  */
}

.regional_table /deep/ .el-table .el-table__cell {
  padding: 0;
}

/* 如果表头或其他部分需要特殊透明处理 */
.regional_table /deep/ .el-table__header-wrapper {
  background-color: rgba(255, 255, 255, 0.1);
  /* 表头轻微透明 */
}

.logo-text-container {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  /* justify-content: space-between;  */
  padding: 10px 0;
  /* 上下间距 */
}

.logo-text {
  color: white;
  /* 文字颜色为白色 */
  margin-left: 1rem;
}

/* 按钮样式 */
.module1-yhr-button-container {
  display: flex;
  justify-content: center;
}

.module1-yhr-custom-btn {
  width: 8.7%;
  height: 2rem;
  background-size: cover;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background-color: transparent;
  color: #fff;
  margin: 0 1rem;
  font-size: 16px;
}

/* 提交按钮背景图片 */
.module1-yhr-custom-btn:first-child {
  background-image: url('../assets/img/module1/button-tijiao.png');
}

.module1-yhr-custom-btn:nth-child(2) {
  /* background-image: url('../assets/img/module1/button-bohui.png'); */
  background-image: url('../assets/img/module1/button-tijiao.png');
}

.module1-yhr-custom-btn:nth-child(3) {
  background-image: url('../assets/img/module1/button-tijiao.png');
}

.module1-yhr-custom-btn:last-child {
  background-image: url('../assets/img/module1/button-tijiao.png');
}

/* 鼠标悬停效果 */
.module1-yhr-custom-btn:hover {
  opacity: 0.8;
}

.table::-webkit-scrollbar {
  width: 2px;
}

.table::-webkit-scrollbar {
  background-color: rgba(0, 16, 29, 0.5) !important;
}

.table::-webkit-scrollbar-thumb {
  background: #0378FF;
  border-radius: 10px;
}

/* 分析结果区域核心样式优化 */
.analysis-results {
  background: rgba(0, 0, 0, 0.7);
  padding: 15px;
  /* 稍微减小内边距 */
  border-radius: 8px;
  z-index: 1000;
  width: 85%;
  /* margin: 15px auto; */
  margin: 0px auto 15px auto;
  position: relative;
  box-shadow: 0 0 15px rgba(0, 120, 255, 0.2);
}

.analysis-text-box {
  background: rgba(10, 20, 35, 0.6);
  border: 1px solid rgba(0, 120, 255, 0.3);
  border-radius: 6px;
  padding: 15px;
  /* 减小内边距 */
  color: #e6e6e6;
  font-size: 14px;
  line-height: 1.5;
  /* 关键优化：将行高从1.8减小到1.5 */
  max-height: 300px;
  /* 新增：限制最大高度 */
  overflow-y: auto;
  /* 超出时显示滚动条 */
}

/* 分段样式优化 */
.analysis-paragraph {
  margin: 0 0 8px 0;
  /* 减小段落间距 */
  text-indent: 0;
}

/* 成功状态 - 亮绿色 */
::v-deep .analysis-success {
  color: #52c41a !important;
  /* !important 确保优先级（可选，若样式被覆盖则加） */
  font-weight: 500;
}

/* 失败状态 - 亮红色 */
::v-deep .analysis-failed {
  color: #ff4d4f !important;
  font-weight: 500;
}

/* 处理建议样式 */
.analysis-suggestion {
  margin-top: 10px;
  padding-top: 8px;
  border-top: 1px dashed rgba(255, 255, 255, 0.1);
  color: #91d5ff;
  font-size: 13px;
  /* 稍微减小建议文字大小 */
}

/* 分析中提示样式 */
.analyzing-tip {
  color: #faad14;
  /* 更鲜艳的橙色 */
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 其他样式保持不变 */
.loading-icon {
  animation: blink 1.2s infinite alternate;
}

@keyframes blink {
  from {
    opacity: 0.5;
    transform: scale(0.9);
  }

  to {
    opacity: 1;
    transform: scale(1.1);
  }
}

.error-tip {
  color: #ff4d4f;
  display: flex;
  align-items: center;
  gap: 8px;
}

.error-icon {
  background: #ff4d4f;
  color: white;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  margin-right: 5px;
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  width: 18px;
  height: 18px;
  cursor: pointer;
  transition: all 0.2s;
  opacity: 0.8;
}

.close-btn:hover {
  opacity: 1;
  transform: scale(1.1);
}
</style>


<style lang="scss" scoped>
@import "../assets/demo/index.scss";
</style>